import os
import sys
import time

from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QPainter, QPaintEvent, QPixmap
from PyQt5.QtWidgets import QMessageBox
from zhdate import ZhDate
from datetime import datetime

from UI import *
from Data import *


class Gui(Ui_Form):
    # 数据格式
    # weather_infos = {"城市": "省,市,县", "今天": ["天气", "温度", "紫外线", "湿度", "体感"], "明天": ["天气", "温度"], "后天": ["天气", "温度"], "大后天": ["天气", "温度",]}

    def __init__(self, Form):
        super(Gui, self).__init__()
        # 自动查询状态
        self.auto_cheak_state: bool = False
        # 实例化数据类
        self.data = Weather_data()
        # 美化设计
        Form.setWindowIcon(QIcon("res/icon.png"))
        # Form.setWindowFlags(Qt.FramelessWindowHint)
        self.setupUi(Form)
        self.pushButton_location.setIcon(QIcon("res/location1.png"))
        self.pushButton_search.setIcon(QIcon("res/search1.png"))
        icon = QIcon('res/logo.jpg')
        self.label_logo.setPixmap(icon.pixmap(self.label_logo.size()))

        # 消息盒子
        self.messagebox = QMessageBox()
        self.messagebox.setText("请检查网络设置后重试")
        self.messagebox.setWindowTitle("出错了捏")
        self.messagebox.setWindowIcon(QIcon("res/icon.png"))
        self.messagebox.setIcon(QMessageBox.Information)

        self.messagebox_search = QMessageBox()
        self.messagebox_search.setText("请选择城市后再试")
        self.messagebox_search.setWindowTitle("出错了捏")
        self.messagebox_search.setWindowIcon(QIcon("res/icon.png"))
        self.messagebox_search.setIcon(QMessageBox.Information)

        self.messagebox_warn = QMessageBox()
        self.messagebox_warn.setText("此区域目前不可查")
        self.messagebox_warn.setWindowTitle("出错了捏")
        self.messagebox_warn.setWindowIcon(QIcon("res/icon.png"))
        self.messagebox_warn.setIcon(QMessageBox.Information)

        # comBox初始化
        self.comboBox_pro.setEditable(True)
        self.comboBox_city.setEditable(True)
        self.comboBox_country.setEditable(True)
        self.comboBox_pro.addItem("")
        try:
            self.cities = self.data.get_cities_name()
            for city in self.cities:
                self.comboBox_pro.addItem(city[0])
        except requests.exceptions.ConnectionError:
            self.messagebox.show()

        # 信号
        self.pushButton_location.pressed.connect(self.pushButton_location_pressed)
        self.pushButton_location.released.connect(self.pushButton_location_released)
        self.pushButton_search.pressed.connect(self.pushButton_search_pressed)
        self.pushButton_search.released.connect(self.pushButton_search_released)
        self.timer = QTimer()
        self.timer.timeout.connect(self.change_background_img)
        self.timer.start(1000)
        self.timer_auto_cheak = QTimer()
        self.timer_auto_cheak.timeout.connect(self.auto_cheak)
        self.timer_auto_cheak.start(300000)
        self.comboBox_pro.currentTextChanged.connect(self.load_city)
        self.comboBox_city.currentTextChanged.connect(self.load_country)


    # 槽函数
    def pushButton_location_pressed(self):
        self.pushButton_location.setIcon(QIcon("res/location2.png"))

    def pushButton_location_released(self):
        try:
            count = 0
            while count < 5:
                infos = self.data.get_local_data()
                if infos["城市"] and infos["现在"] and infos["今天"] and infos["明天"] and infos["后天"] and infos["大后天"]:
                    self.load_weather_info(infos)
                    break
                else:
                    count += 1
            if count >= 5:
                self.messagebox.show()
                count = 0

        except requests.exceptions.ConnectionError:
            self.messagebox.show()
        self.pushButton_location.setIcon(QIcon("res/location1.png"))

    def pushButton_search_pressed(self):
        self.pushButton_search.setIcon(QIcon("res/search2.png"))

    def pushButton_search_released(self):
        try:
            pro = self.comboBox_pro.currentText()
            if "特别行政区" in pro:
                self.messagebox_warn.show()
                self.pushButton_search.setIcon(QIcon("res/search1.png"))
                return
            city = self.comboBox_city.currentText()
            country = self.comboBox_country.currentText().rstrip("县")
            if pro and city:
                count = 0
                while count < 5:
                    infos = self.data.get_data(pro, city, country)
                    if infos["城市"] and infos["现在"] and infos["今天"] and infos["明天"] and infos["后天"] and infos["大后天"]:
                        self.load_weather_info(infos)
                        break
                    else:
                        count += 1
                if count >= 5:
                    self.messagebox.show()
                    count = 0
            else:
                self.messagebox_search.show()
                self.auto_cheak_state = False
        except requests.exceptions.ConnectionError:
            self.messagebox.show()
        self.pushButton_search.setIcon(QIcon("res/search1.png"))

    # 背景加载槽函数，包括时间显示，每1秒钟调用一次
    def change_background_img(self):
        state = 0   # 特殊日期的状态
        cn_date = str(ZhDate.from_datetime((datetime(time.localtime(time.time()).tm_year, time.localtime(time.time()).tm_mon, time.localtime(time.time()).tm_mday))))
        special_date = ["1月16日", "11月28日", "7月23日", "4月15日", "6月28日", "8月28日", "11月04日", "1月27日",] # 特殊日期的列表
        for date in special_date:
            if date in cn_date:
                state = 1
            else:
                state = 0
        current_time = time.localtime(time.time())
        if current_time.tm_min >= 10:
            self.label_today.setText(str(current_time.tm_hour)+":"+str(current_time.tm_min))
        else:
            self.label_today.setText(str(current_time.tm_hour) + ":" + "0" + str(current_time.tm_min))
        self.label_date.setText(str(current_time.tm_year)+"年"+str(current_time.tm_mon)+"月"+str(current_time.tm_mday)+"日")
        if state == 0:
            if 7 <= current_time.tm_hour < 19:
                Form.setStyleSheet("#Form{\n"
                                   "    background-image:url(\"res/daytime.jpg\");\n"
                                   "     background-repeat: no-repeat;\n"
                                   "     background-position: center;\n"
                                   "}")
            else:
                Form.setStyleSheet("#Form{\n"
                                   "    background-image:url(\"res/night.jpg\");\n"
                                   "     background-repeat: no-repeat;\n"
                                   "     background-position: center;\n"
                                   "}")
        # elif 判断日期什么日子
        else:
            Form.setStyleSheet("#Form{\n"
                               "    background-image:url(\"res/birthday.jpg\");\n"
                               "     background-repeat: no-repeat;\n"
                               "     background-position: center;\n"
                               "}")

    # 加载天气信息槽函数
    def load_weather_info(self, infos):
        print(infos)
        city = infos["城市"].split(",")
        if len(city) < 3:
            for count in range(3 - len(city)):
                city.append("")
        elif len(city) > 3:
            while len(city) > 3:
                city.pop()
        self.comboBox_pro.setCurrentText(city[0].strip(" "))
        self.comboBox_city.setCurrentText(city[1].strip(" "))
        self.comboBox_country.setCurrentText(city[2].strip(" "))
        self.label_weather.setText(infos["现在"][0])
        self.label_temp.setText("当前温度:" + infos["现在"][1]+"℃")
        self.label_ul.setText(infos["现在"][2])
        self.label_humidity.setText("湿度:" + infos["现在"][3])
        self.label_body_fell.setText("体感温度:" + str(infos["现在"][4])+"°")
        if "晴" in infos["现在"][0]:
            icon = QIcon('res/sunday.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))
        elif "雨" in infos["现在"][0]:
            icon = QIcon('res/rain.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))
        elif "云" in infos["现在"][0] or "阴" in infos["现在"][0] or "雾" in infos["现在"][0]:
            icon = QIcon('res/cloud.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))
        elif "雪" in infos["现在"][0]:
            icon = QIcon('res/snow.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))
        elif "雷" in infos["现在"][0]:
            icon = QIcon('res/thunder.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))
        else:
            icon = QIcon('res/reload2.png')
            self.label_weather_pic.setPixmap(icon.pixmap(self.label_weather_pic.size()))

        self.label_today2.setText("今天")
        self.label_temp2.setText(str(infos["今天"][0])+"至"+str(infos["今天"][1])+"℃")
        if "晴" in infos["今天"][2]:
            icon = QIcon('res/sunday.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))
        elif "雨" in infos["今天"][2]:
            icon = QIcon('res/rain.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))
        elif "云" in infos["今天"][2] or "阴" in infos["今天"][2] or "雾" in infos["今天"][2]:
            icon = QIcon('res/cloud.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))
        elif "雪" in infos["今天"][2]:
            icon = QIcon('res/snow.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))
        elif "雷" in infos["今天"][2]:
            icon = QIcon('res/thunder.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))
        else:
            icon = QIcon('res/reload2.png')
            self.label_weather_pic2.setPixmap(icon.pixmap(self.label_weather_pic2.size()))

        self.label_tomorrow.setText("明天")
        self.label_tomorrow_temp.setText(str(infos["明天"][0]) + "至" + str(infos["明天"][1])+"℃")
        if "晴" in infos["明天"][2]:
            icon = QIcon('res/sunday.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))
        elif "雨" in infos["明天"][2]:
            icon = QIcon('res/rain.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))
        elif "云" in infos["明天"][2] or "阴" in infos["明天"][2] or "雾" in infos["明天"][2]:
            icon = QIcon('res/cloud.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))
        elif "雪" in infos["明天"][2]:
            icon = QIcon('res/snow.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))
        elif "雷" in infos["明天"][2]:
            icon = QIcon('res/thunder.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))
        else:
            icon = QIcon('res/reload2.png')
            self.label_tomorrow_weather_pic.setPixmap(icon.pixmap(self.label_tomorrow_weather_pic.size()))

        self.label_aft.setText("后天")
        self.label_aft_temp.setText(str(infos["后天"][0]) + "至" + str(infos["后天"][1])+"℃")
        if "晴" in infos["后天"][2]:
            icon = QIcon('res/sunday.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))
        elif "雨" in infos["后天"][2]:
            icon = QIcon('res/rain.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))
        elif "云" in infos["后天"][2] or "阴" in infos["后天"][2] or "雾" in infos["后天"][2]:
            icon = QIcon('res/cloud.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))
        elif "雪" in infos["后天"][2]:
            icon = QIcon('res/snow.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))
        elif "雷" in infos["后天"][2]:
            icon = QIcon('res/thunder.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))
        else:
            icon = QIcon('res/reload2.png')
            self.label_aft_wheather_pic.setPixmap(icon.pixmap(self.label_aft_wheather_pic.size()))

        self.label_td.setText("大后天")
        self.label_td_temp.setText(str(infos["大后天"][0]) + "至" + str(infos["大后天"][1])+"℃")
        if "晴" in infos["大后天"][2]:
            icon = QIcon('res/sunday.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        elif "雨" in infos["大后天"][2]:
            icon = QIcon('res/rain.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        elif "云" in infos["大后天"][2] or "阴" in infos["大后天"][2] or "雾" in infos["大后天"][2]:
            icon = QIcon('res/cloud.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        elif "雪" in infos["大后天"][2]:
            icon = QIcon('res/snow.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        elif "雷" in infos["大后天"][2]:
            icon = QIcon('res/thunder.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        else:
            icon = QIcon('res/reload2.png')
            self.label_td_wheather_pic.setPixmap(icon.pixmap(self.label_td_wheather_pic.size()))
        self.auto_cheak_state = True

    # 加载市级城市槽函数，在combox_pro框中信息改变使调用
    def load_city(self):
        pro = self.comboBox_pro.currentText()
        self.comboBox_city.clearEditText()
        self.comboBox_country.clearEditText()
        for i in range(self.comboBox_city.count()):
            self.comboBox_city.removeItem(0)
        for city in self.cities:
            if pro in city:
                for j in range(1, len(city)):
                    if "\n" not in city[j]:
                        self.comboBox_city.addItem(city[j])
                break

    # 加载县级城市槽函数,在combox_city改变时调用
    def load_country(self):
        city_name = self.comboBox_city.currentText()
        for i in range(self.comboBox_country.count()):
            self.comboBox_country.removeItem(0)
        for cities in self.cities:
            if city_name in cities:
                index = cities.index(city_name)
                countries = cities[index+1].split("\n")
                for name in countries:
                    self.comboBox_country.addItem(name)
                break

    # 自动查询槽函数
    def auto_cheak(self):
        if self.auto_cheak_state == True:
            self.pushButton_search_released()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Gui(Form)
    Form.show()
    sys.exit(app.exec_())
